package com.eatme.web.util.wechat;

import com.alibaba.fastjson2.JSON;
import com.eatme.web.app.coupon.common.exception.AppException;
import com.eatme.web.util.wechat.vo.WxBaseResponse;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;
import java.util.Objects;

import static com.eatme.web.util.wechat.v2.sdk.WXPayConstants.USER_AGENT;
@Component
public class WXBaseService {

    @Autowired
    public StringRedisTemplate redisTemplate;

    BasicHttpClientConnectionManager connManager = new BasicHttpClientConnectionManager(
            RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.getSocketFactory())
                    .register("https", SSLConnectionSocketFactory.getSocketFactory())
                    .build(),
            null,
            null,
            null
    );

    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(8*1000).setConnectTimeout(6*1000).build();


    HttpClient httpClient = HttpClientBuilder.create()
            .setConnectionManager(connManager)
            .build();

    private static final Logger LOG = LoggerFactory.getLogger(WXBaseService.class);
    protected final static String APPID =  "wx96768ef70ba3b1db";//"wxcc9d03604da481f6";

    protected final static String SECRET = "3be72832eba74011c1f76ca00d456797";//""ee34d0f0fe4662fe2152f4016e463e18";

    protected final static String MCHID = "1519033281";

    private final static String KEY = "";

    public WxBaseResponse jscode2session(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code";
        url = url.replace("APPID", APPID);
        url = url.replace("SECRET", SECRET);
        url = url.replace("JSCODE", code);
        HttpGet httpGet = new HttpGet(url);

        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(8*1000).setConnectTimeout(6*1000).build();
        httpGet.setConfig(requestConfig);
        httpGet.addHeader("Content-Type", "text/xml");
        // httpGet.addHeader("User-Agent", USER_AGENT + " " + config.getMchID());
        httpGet.addHeader("User-Agent", USER_AGENT + " " + MCHID);
        HttpResponse httpResponse = null;
        try {
            httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            String result = EntityUtils.toString(httpEntity, "UTF-8");
            LOG.info("jscode2session result: {}",result);
            return JSON.parseObject(result, WxBaseResponse.class);
        } catch (Exception e) {
            LOG.info("Exception: {}",e);
            throw new AppException(e);
        }

    }


    public WxBaseResponse getAccessToken()throws Exception {
        String wx_accessTokenKey = "wx_accessTokenKey";
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
        url = url.replace("APPID", APPID);
        url = url.replace("APPSECRET", SECRET);
        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(requestConfig);
        httpGet.addHeader("Content-Type", "text/xml");
        // httpGet.addHeader("User-Agent", USER_AGENT + " " + config.getMchID());
        httpGet.addHeader("User-Agent", USER_AGENT + " " + MCHID);
        HttpResponse httpResponse = httpClient.execute(httpGet);
        HttpEntity httpEntity = httpResponse.getEntity();
        String result = EntityUtils.toString(httpEntity, "UTF-8");
        LOG.info("getAccessToken result: {}",result);
        WxBaseResponse response = JSON.parseObject(result, WxBaseResponse.class);
        return response;
    }

    public static void main(String[] args) throws Exception {
        new WXBaseService().jscode2session("123");
    }
}
